package com.zjnx.train.tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import javax.servlet.ServletContext;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SocketThread extends Thread {

	Integer count = 0;
	private ServletContext servletContext;
	private ServerSocket serverSocket;

	public SocketThread(ServerSocket serverSocket, ServletContext servletContext) {
		this.servletContext = servletContext;
		// 从web.xml中context-param节点获取socket端口
		String port = this.servletContext.getInitParameter("socketPort");
		if (serverSocket == null) {
			try {
				this.serverSocket = new ServerSocket(Integer.parseInt(port));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
//        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
//        myBussiness = ((MyBussiness) wac.getBean("myBussiness"));
	}

	public void run() {
		try {
			Integer count = 0;
			while (!this.isInterrupted()) {
				SocketServer.rerfresh();

				Socket socket = serverSocket.accept();
				count++;
				System.out.println("Server SocketThread start:" + count);
				if (socket != null) {
					SocketClient client = new SocketClient();
					client.setSocket(socket);
					SocketServer.socketClientList.add(client);

					System.out.println("new commer:" + socket.getRemoteSocketAddress().toString());
					SocketServer.invoke(socket);
				}
			}
		} catch (Exception ex) {
			System.out.println("SocketThread err:" + ex.getMessage());
		}

	}

	public void closeServerSocket() {
		try {
			if (serverSocket != null && !serverSocket.isClosed()) {
				serverSocket.close();
				SocketServer.destroyedTimer();
			}

		} catch (Exception ex) {
			System.out.println("SocketThread err:" + ex.getMessage());
		}
	}
}
